import XtxMessage from "./xtxMessage/index";
import { createElement } from "react";
import { createRoot } from "react-dom/client";

const divMessage = document.createElement("div");
divMessage.setAttribute("class", "xtx-message-Container");
document.body.appendChild(divMessage);

// 2. 导出一个函数
export default ({
  type,
  text,
  showClose = false,
  duration = 2000,
}: {
  type: string;
  text: string;
  showClose?: boolean;
  duration: number;
}) => {
  let timer: any = null;
  const root = createRoot(divMessage);
  const vender = createElement(XtxMessage, { type, text, showClose });

  // 3. 渲染组件
  root.render(vender);

  if (showClose) {
    // 使用 MutationObserver 监听 DOM 变化，确保关闭按钮渲染后可以获取到
    const observer = new MutationObserver(() => {
      const rooot = document.querySelector(
        ".xtx-message-Container"
      ) as HTMLDivElement;

      if (rooot) {
        const guanbi = rooot.querySelector(".guanbi") as HTMLDivElement;
        guanbi.addEventListener("click", function () {
          root.unmount(); // 卸载组件
          clearTimeout(timer);
          observer.disconnect();
        });
      }
    });

    // 开始监听
    observer.observe(document.body, { childList: true, subtree: true });
  }

  // 6. 创建定时器然后销毁
  timer = setTimeout(() => {
    root.unmount();
    clearTimeout(timer);
  }, duration);
};
